#include "FT6336.h"




int FT6336_Class::begin(TwoWire &port, uint8_t addr)
{
    _i2cPort = &port;
    _address = addr;
    uint8_t val;
    _readByte(FT6336_VENDID_REG, 1, &val);
    if (val != FT6336_VENDID) {
         return false;
    }
    _readByte(FT6336_CHIPID_REG, 1, &val);
    if ((val != FT6336U_CHIPID)) {
        return false;
    }
    _init = true;
    return true;
}

// valid touching detect threshold.
void FT6336_Class::adjustTheshold(uint8_t thresh)
{
    if (!_init)return;
    _writeByte(FT6336_THRESHHOLD_REG, 1, &thresh);
}

TP_Point FT6336_Class::getPoint(uint8_t num)
{
    if (!_init) return TP_Point(0, 0);
    _readRegister();
    if ((_touches == 0) || (num > 1)) {
        return TP_Point(0, 0);
    } else {
        return TP_Point(_x[num], _y[num]);
    }
}

uint8_t FT6336_Class::touched()
{
    if (!_init)return 0;
    uint8_t val = 0;
    _readByte(FT6336_TOUCHES_REG,1,&val);
    return val > 2 ? 0: val;
}

void FT6336_Class::enterSleepMode()
{
    if (!_init)return;
    uint8_t val = FT6336_SLEEP_IN;
    _writeByte(FT6336_POWER_REG, 1, &val);
}

void FT6336_Class::enterMonitorMode()
{
    if (!_init)return;
    uint8_t val = FT6336_MONITOR;
    _writeByte(FT6336_POWER_REG, 1, &val);
}

void FT6336_Class::_readRegister()
{
    _readByte(DEVIDE_MODE, 16, _data);
    _touches = _data[TD_STATUS];
    if ((_touches > 2) || (_touches == 0)) {
        _touches = 0;
        return;
    }
    for (uint8_t i = 0; i < 2; i++) {
        _x[i] = _data[TOUCH1_XH + i * 6] & 0x0F;
        _x[i] <<= 8;
        _x[i] |= _data[TOUCH1_XL + i * 6];
        _y[i] = _data[TOUCH1_YH + i * 6] & 0x0F;
        _y[i] <<= 8;
        _y[i] |= _data[TOUCH1_YL + i * 6];
        _id[i] = _data[TOUCH1_YH + i * 6] >> 4;
    }
}

